//
//  ViewController.m
//  TestPhoto
//
//  Created by Ethan on 2017/11/28.
//  Copyright © 2017年 Ethan. All rights reserved.
//

#import "ViewController.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface ViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

/**
 打开相机

 @param sender
 */
- (IBAction)xiangji:(id)sender {

	NSString *mediaType = AVMediaTypeVideo;
	AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
	if(authStatus == AVAuthorizationStatusAuthorized) {
		
		[self toXiangce:UIImagePickerControllerSourceTypeCamera];
	} else{
		
		__block typeof(self) wSelf = self;
		[AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
			if(granted){
				//TODO:弹窗点击允许后 需要在主线程里做其他操作，不然会没反应
				dispatch_async(dispatch_get_main_queue(), ^{
					[wSelf toXiangce:UIImagePickerControllerSourceTypeCamera];
				});
			} else {
				//不允许
				dispatch_async(dispatch_get_main_queue(), ^{
					[wSelf showAlertWithType:UIImagePickerControllerSourceTypeCamera];
				});
			}
		}];
	}
	
}

/**
 打开相册

 @param sender
 */
- (IBAction)xiangce:(id)sender {
	
	PHAuthorizationStatus statuss = [PHPhotoLibrary authorizationStatus];
	if (statuss != PHAuthorizationStatusAuthorized) {
		//没权限, 请求权限
		__block typeof(self) wSelf = self;
		[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
			
			if (status == PHAuthorizationStatusAuthorized) {
				
				//TODO:弹窗点击允许后 需要在主线程里做其他操作，不然会没反应
				dispatch_async(dispatch_get_main_queue(), ^{
					[wSelf toXiangce:UIImagePickerControllerSourceTypePhotoLibrary];
				});
				
			}else{
				//不允许
				dispatch_async(dispatch_get_main_queue(), ^{
					[wSelf showAlertWithType:UIImagePickerControllerSourceTypePhotoLibrary];
				});
			}

		}];
	}else{
		//已经有权限，直接打开相册
		[self toXiangce:UIImagePickerControllerSourceTypePhotoLibrary];
	}
	
}


- (void)toXiangce:(UIImagePickerControllerSourceType)type{
	UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
	imagePickerController.delegate = self;
	imagePickerController.allowsEditing = YES;
	if ([UIImagePickerController isSourceTypeAvailable:type]) {
		imagePickerController.sourceType = type;
	}
	[self presentViewController:imagePickerController animated:YES completion:nil];
}

// 取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[picker dismissViewControllerAnimated:YES completion:nil];
}

// 选择完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	
	UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width,
																		   self.view.frame.size.height - 20)];
	imageView.contentMode = UIViewContentModeScaleAspectFit;
	[self.view addSubview:imageView];
	[self.view sendSubviewToBack:imageView];
	if ([info objectForKey:UIImagePickerControllerEditedImage] != nil) {
		imageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
	}
	if ([info objectForKey:UIImagePickerControllerMediaType] != nil) {
		imageView.image = info[UIImagePickerControllerOriginalImage];
	}
	[picker dismissViewControllerAnimated:YES completion:nil];
}

/**
 提示用户设置

 @param type UIImagePickerControllerSourceType
 */
- (void)showAlertWithType:(UIImagePickerControllerSourceType)type{
	
	NSString *title = @"";
	NSString *message = @"";
	NSString *urlString = @"";
	
	if (type == UIImagePickerControllerSourceTypeCamera) {
		title = @"无法为老年人使用相机";
		message = @"请在iPhone的\"设置-隐私-相机\"中允许访问相机";
		urlString = @"prefs:root=Privacy&path=CAMERA";
		
	}else if(type == UIImagePickerControllerSourceTypePhotoLibrary){
		title = @"无法为老年人使用相册";
		message = @"请在iPhone的\"设置-隐私-照片\"中允许访问照片";
		urlString = @"prefs:root=Privacy&path=PHOTOS";
	}
	
	UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
																			 message:message
																	  preferredStyle:UIAlertControllerStyleAlert];
	
	[alertController addAction:[UIAlertAction actionWithTitle:@"取消"
														style:UIAlertActionStyleCancel
													  handler:^(UIAlertAction * _Nonnull action) {
														  NSLog(@"点击取消");
	}]];

	[alertController addAction:[UIAlertAction actionWithTitle:@"去设置"
														style:UIAlertActionStyleDefault
													  handler:^(UIAlertAction * _Nonnull action) {
														//这里需要配置下，在URL Types里添加
														NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
														[[UIApplication sharedApplication] openURL:url];
														[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
	}]];
	
	[self presentViewController:alertController animated:YES completion:nil];
}

@end
